<template>
  <div class="profile">
    <van-nav-bar
      left-arrow
      title="个人信息"
      @click-left="$router.push('/user')"
    ></van-nav-bar>
    <van-cell-group>
      <van-uploader :before-read="beforeRead" :after-read="afterRead">
        <van-cell is-link title="头像" center>
          <van-image
            slot="default"
            fit="cover"
            round
            :src="userProfile.photo"
          />
        </van-cell>
      </van-uploader>
      <van-cell
        is-link
        title="昵称"
        :value="userProfile.name"
        @click="nameClick"
      />
    </van-cell-group>
    <van-cell-group style="margin-top:12px">
      <van-cell
        is-link
        title="性别"
        :value="userProfile.gender === 0 ? '男' : '女'"
        @click="genderClick"
      />
      <van-cell
        is-link
        title="生日"
        :value="userProfile.birthday | fotmatBirthday"
        @click="birthdayClick"
      />
    </van-cell-group>
    <div class="logout">
      <span @click="logout">退出登录</span>
    </div>
    <!-- 昵称修改弹框 -->
    <van-popup class="my-popup" v-model="showName" position="right">
      <van-nav-bar
        left-arrow
        right-text="保存"
        title="修改昵称"
        @click-left="showName = false"
        @click-right="saveName"
      />
      <van-field v-model="nameInput"></van-field>
    </van-popup>
    <!-- 性别选择弹框 -->
    <van-action-sheet
      v-model="showGender"
      :actions="genderActions"
      cancel-text="取消"
      close-on-click-action
      @select="genderSelect"
    ></van-action-sheet>
    <!-- 生日选择弹框 -->
    <van-popup v-model="showBirthday" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="选择生日"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirm"
        @cancel="cancel"
      ></van-datetime-picker>
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import dayjs from 'dayjs'
import { userProfilePatch, userPhoto } from '@/api/user.js'
export default {
  name: 'Profile',
  data () {
    return {
      showName: false,
      nameInput: '',
      showGender: false,
      genderActions: [
        { name: '男', value: 0 },
        { name: '女', value: 1 }
      ],
      showBirthday: false,
      currentDate: new Date(),
      minDate: new Date(1950, 0, 1),
      maxDate: new Date()
    }
  },
  methods: {
    // 退出登录
    logout () {
      this.$dialog
        .confirm({ title: '标题', message: '您确定要退出登录吗？' })
        .then(() => {
          this.$store.commit('user/setToken', '')
          this.$router.push('/login')
          this.$toast.success('退出成功')
        })
        .catch(() => {})
    },
    // 上传头像前限制大小和格式
    beforeRead (file) {
      const _image = file.type === 'images/png' || file.type === 'images/jpeg'
      const limit1M = file.size / 1024 / 1024 < 1
      if (!_image) {
        this.$toast.fail('请上传 png 或 jpg 格式的图片')
      }
      if (!limit1M) {
        this.$toast.fail('请上传 1M 以内的图片')
      }
      return _image && limit1M
    },
    // 修改头像
    async afterRead (fileRes) {
      console.log(fileRes)
      const formData = new FormData()
      formData.append('photo', fileRes.file)
      const res = await userPhoto(formData)
      this.$toast.success('修改成功')
      this.$store.commit('user/editUserProfile', ['photo', res.data.photo])
    },
    // 封装修改个人资料方法
    async editUserInfo (obj) {
      await userProfilePatch({ [obj.key]: obj.value })
      this.$store.commit('user/editUserProfile', [obj.key, obj.value])
      this.$toast.success('修改成功')
    },
    // 打开修改昵称弹框
    nameClick () {
      this.showName = true
      this.nameInput = this.userProfile.name
    },
    // 保存修改昵称
    saveName () {
      if (this.nameInput === this.userProfile.name) {
        return this.$toast.fail('不能和当前昵称一样')
      }
      if (this.nameInput === '') {
        return this.$toast.fail('昵称不能为空')
      }
      this.editUserInfo({
        key: 'name',
        value: this.nameInput
      })
      this.showName = false
      this.$toast.success('修改成功')
    },
    // 打开性别选择弹框
    genderClick () {
      this.showGender = true
      this.genderActions[this.userProfile.gender].disabled = true
      this.genderActions[1 - this.userProfile.gender].disabled = false
    },
    // 修改性别
    genderSelect (item) {
      this.editUserInfo({ key: 'gender', value: item.value })
    },
    // 打开生日选择弹框
    birthdayClick () {
      this.showBirthday = true
      this.currentDate = new Date(this.userProfile.birthday)
    },
    // 生日弹框点击确定
    confirm () {
      this.editUserInfo({ key: 'birthday', value: this.currentDate })
      this.showBirthday = false
    },
    // 生日弹框点击取消
    cancel () {
      this.showBirthday = false
    }
  },
  computed: {
    ...mapState('user', ['userProfile'])
  },
  created () {
    this.$store.dispatch('user/getUserProfile')
  },
  filters: {
    fotmatBirthday (time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  }
}
</script>

<style lang="less" scoped>
.profile {
  background: #f8f8f8;

  .van-uploader {
    width: 100%;

    ::v-deep .van-uploader__input-wrapper {
      width: 100%;
    }
  }

  .van-image {
    display: block;
    float: right;
    width: 30px;
    height: 30px;
  }

  .van-cell__title {
    width: 50px;
    flex: none;
  }

  .logout {
    text-align: center;
    position: absolute;
    left: 0;
    bottom: 30px;
    width: 100%;
    color: @geek-color;
  }

  .my-popup {
    width: 100%;
    height: 100%;

    ::v-deep .van-nav-bar__text {
      color: @geek-color;
    }

    ::v-deep .van-field__control {
      background: @geek-gray-color;
      padding: 10px;
      border-radius: 4px;
    }
  }
}
</style>
